<!-- 系列 -->
<template>
  <div class="app-container">
    <!-- 检索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="系列名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入系列名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表头操作 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openInnerDialog('add')"
          v-hasPermi="['system:role:add']"
        >
          新增
        </el-button>
      </el-col>
    </el-row>
    <el-table class="table_box" v-loading="loading" :data="tableList">
      <!-- height="calc(100vh - 230px)" -->
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column
        label="一级系列名称"
        prop="name"
        align="center"
        width="150"
      />
      <el-table-column
        label="二级系列名称"
        prop="parentName"
        align="center"
        width="150"
      />
      <el-table-column
        label="系列图片"
        prop="picUrl"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <img
            class="table_pic_box"
            :src="scope.row.picUrl.split(',')[0]"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column label="系列介绍" prop="introduction" align="center" />
      <el-table-column
        label="是否首页展示"
        prop="portalPageShow"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.portalPageShow == 1 ? 'primary' : 'info'">
            {{ scope.row.portalPageShow == 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="是否产品展示"
        prop="productShow"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.productShow == 1 ? 'primary' : 'info'">
            {{ scope.row.productShow == 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openInnerDialog('edit', scope.row)"
            v-hasPermi="['system:role:edit']"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div slot="footer" class="dialog-footer">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 新增系列弹框 -->
    <el-dialog
      custom-class="custom_inner_dialog_box"
      :title="(enterInnerType === 'add' ? '新增' : '修改') + '产品系列'"
      :visible.sync="innerVisible"
      v-if="innerVisible"
      width="480px"
      append-to-body
      destroy-on-close
      @close="dialogColse"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        v-loading="submitLoading"
      >
        <el-form-item label="系列层级" prop="level">
          <el-select
            v-model="formData.level"
            placeholder="请选择系列层级"
            @change="levelChange"
          >
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.level === 2"
          label="父系列名称"
          prop="parentId"
        >
          <el-select v-model="formData.parentId" placeholder="请选择父系列名称">
            <el-option
              v-for="item in parentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系列名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入系列名称"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            placeholder="请输入排序"
            :min="0"
            :max="999"
          />
        </el-form-item>
        <el-form-item label="是否首页展示">
          <el-switch
            v-model="formData.portalPageShow"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否产品展示">
          <el-switch
            v-model="formData.productShow"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="系列图片" prop="picUrl">
          <el-upload
            :class="{ 'hide_upload': formData.picUrl }"
            ref="upload"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :headers="upload.headers"
            :action="upload.url"
            list-type="picture-card"
            :file-list="picUrlBack"
            :on-success="(res, file) => handleAvatarSuccess(res, file)"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file, fileList) => handleRemove(file, fileList)"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div v-if="formData.level === 1">推荐图片宽高比为3:1</div>
          <div v-if="formData.level === 2">推荐图片宽高比为1:1</div>
        </el-form-item>
        <el-form-item label="产品介绍" prop="introduction">
          <el-input
            v-model="formData.introduction"
            type="textarea"
            placeholder="请输入产品介绍"
            maxlength="500"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          保 存
        </el-button>
        <el-button @click="dialogColse">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图片查看弹框 -->
    <el-dialog :visible.sync="imgDialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import {
  productSeriesList,
  productSeriesSave,
  productSeriesUpdate,
  productSeriesDelete,
  productSeriesQueryById,
} from "@/api/useMenu/product";
import { getToken } from "@/utils/auth";
import { UPLOADURL } from "@/api/useMenu/config";
export default {
  name: "ProductSeries",
  data() {
    return {
      visible: false, //弹层状态
      loading: false, //表格加载状态
      tableList: [], //表格数据
      total: 0, //表格总数据
      // 查询参数
      queryParams: {
        name: "",
        pageNum: 1,
        pageSize: 10,
      },

      submitLoading: false,
      innerVisible: false, //内部弹框状态
      enterInnerType: "", //内部弹框类型 add/edit
      formData: {
        portalPageShow: "0",
        productShow: "0",
      },
      rules: {
        level: [
          {
            required: true,
            message: "请选择系列层级",
            trigger: "change",
          },
        ],
        parentId: [
          {
            required: true,
            message: "请选择父系列名称",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入系列名称",
            trigger: ["blur", "change"],
          },
        ],
        picUrl: [
          {
            required: true,
            message: "请上传系列图片",
            trigger: ["blur", "change"],
          },
        ],
        introduction: [
          {
            required: true,
            message: "请输入产品介绍",
            trigger: ["blur", "change"],
          },
        ],
      },
      // 层级系列下拉数据
      levelOptions: [
        { value: 1, label: "层级一" },
        { value: 2, label: "层级二" },
      ],
      // 父系列下拉数据
      parentOptions: [],
      // 上传参数
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + UPLOADURL,
      },
      // 图片详情弹框
      imgDialogVisible: false,
      dialogImageUrl: "",

      picUrlBack: [], //系列图片回写
    };
  },
  created() {},
  mounted() {
    this.getList();
  },
  methods: {
    // 打开弹框
    async openDialog() {
      this.visible = true;
      await this.getList();
    },
    /** 查询表格数据 */
    async getList() {
      this.loading = true;
      let response = await productSeriesList(this.queryParams);
      this.tableList = response.rows;
      this.total = response.total;
      this.loading = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id, name } = row;
      this.$modal
        .confirm('是否确认删除系列名称为"' + name + '"的数据项？')
        .then(function () {
          return productSeriesDelete(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 获取父系列下拉数据
    async getParentOptions() {
      let { rows } = await productSeriesList({
        pageNum: 1,
        pageSize: 9999,
        level: 1,
      });
      this.parentOptions = rows.map(item => ({
        value: item.id,
        label: item.name,
      }));
    },
    // 打开内部新增弹框
    async openInnerDialog(type = "add", row) {
      this.submitLoading = true;
      this.innerVisible = true;
      this.enterInnerType = type;
      await this.getParentOptions();
      if (type === "edit") {
        // 编辑回写数据
        let { code, data, msg } = await productSeriesQueryById({ id: row.id });
        if (code === 200) {
          this.formData = { ...data };
          this.picUrlBack = data.picUrl.split(",").map(url => ({ url }));
        } else {
          this.$modal.msgError(msg || "接口异常");
        }
      }
      this.submitLoading = false;
    },
    // 系列层级变化
    levelChange(val) {
      if (val === "1") {
        this.formData.parentId = "";
      }
      this.formData.picUrl = ""; //置空系列图片
      this.$refs.upload.clearFiles(); //清空已上传的文件列表
    },
    // 上传成功
    handleAvatarSuccess(res, file) {
      let { msg } = res;
      let result = this.formData.picUrl;
      if (result) {
        // 有值拼接
        result = result + "," + msg;
      } else {
        // 无值赋值
        result = msg;
      }
      this.$set(this.formData, "picUrl", result);
    },
    // 上传之前
    beforeAvatarUpload(file) {
      //   const THIS = this;
      //   const { level } = this.formData;
      //   if (!level) {
      //     this.$message.warning("请您先选择系列层级!");
      //     return false;
      //   }

      const isLt2M = file.size / 1024 / 1024 < 20;

      if (!isLt2M) {
        this.$message.warning("上传图片大小不能超过 20MB!");
        return false;
      }

      return true;

      //   const isSize = new Promise(function (resolve, reject) {
      //     const reader = new FileReader();
      //     reader.readAsDataURL(file);
      //     reader.onload = theFile => {
      //       const image = new Image();
      //       image.src = theFile.target.result;
      //       image.onload = () => {
      //         const { width, height } = image;

      //         let proportion = 3; //一级系列 图片比为 3:1
      //         if (level === 2) {
      //           proportion = 1; //二级系列 图片比为 1:1
      //         }
      //         console.log(width, "width");
      //         console.log(height, "height");
      //         if (width / height !== proportion) {
      //           reject();
      //         } else {
      //           resolve();
      //         }
      //       };
      //     };
      //   }).then(
      //     () => {
      //       return file;
      //     },
      //     () => {
      //       THIS.$message.warning(
      //         `上传图片宽高比为 ${level === 1 ? "3:1" : "1:1"}!`
      //       );
      //       return Promise.reject();
      //       return false; //必须加上return false; 才能阻止
      //     }
      //   );

      //   return isSize;
    },
    handleRemove(file, fileList) {
      let urlList = fileList.map(item => item.response.msg);
      this.$set(this.formData, "picUrl", urlList.join(","));
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imgDialogVisible = true;
    },
    //  提交按钮
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          let { enterInnerType, formData } = this;
          let request =
            enterInnerType === "add" ? productSeriesSave : productSeriesUpdate;
          let { code, msg } = await request(formData);
          if (code === 200) {
            let msg = enterInnerType === "add" ? "新增成功" : "修改成功";
            this.$modal.msgSuccess(msg);
            this.dialogColse();
            this.queryParams.pageNum = 1;
            this.getList();
          } else {
            this.$modal.msgError(msg || "接口异常");
          }
          this.submitLoading = false;
        }
      });
    },
    // Dialog 关闭的回调
    dialogColse() {
      this.innerVisible = false;
      this.formData = {};
      this.picUrlBack = [];
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .table_box {
  .table_pic_box {
    height: 80px;
    // width: 100%;
    // height: 100%;
    // max-width: 450px;
    // max-height: 120px;
  }
}
::v-deep .custom_inner_dialog_box {
  .el-dialog__body {
    max-height: 680px;
    overflow: auto;
  }
  .el-select {
    width: 100% !important;
  }
}

::v-deep .hide_upload {
  .el-upload {
    display: none !important;
  }
}
</style>
